from typing import List

from fastapi import APIRouter, Depends
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import ProjectCreate, ProjectUpdate, ProjectOut as Project, Result, ResultPlus
from crud import project
from utils import resp_200, IdNotExist
from models import Project as ProjectModel

router = APIRouter()


@router.post("/create_project", response_model=Result, summary="新增项目")
async def create_project(project_in: ProjectCreate, db: AsyncSession = Depends(get_db)):
    await project.create(db=db, obj_in=project_in)
    return resp_200(msg=f"添加了{project_in.name}项目.")


@router.get("/", response_model=ResultPlus[Project], summary='查询项目')
async def get_project(pageIndex: int = 1, pageSize: int = 10, queryName: str = '', db: AsyncSession = Depends(get_db)):
    sql1 = select(ProjectModel).offset((pageIndex - 1) * pageSize).limit(pageSize).where(
        ProjectModel.name.like(f'%{queryName}%')).order_by(
        desc(ProjectModel.id))
    result = await db.execute(sql1)
    projectList = result.scalars().all()
    sql2 = select(func.count(distinct(ProjectModel.id)))
    count = await db.scalar(sql2)
    # count = await project.get_number(db)
    # _project = await project.get_multi(db, pageIndex, pageSize)
    db.close()
    return resp_200(data={"count": count, "list": projectList}, msg=f"查询成功")


@router.put('/update_project/{id}', response_model=Result, summary='通过 id 更新接口用例信息')
async def update_project(id: int, project_in: ProjectUpdate,
                         db: AsyncSession = Depends(get_db)):
    rowcount = await project.update(db, id, obj_in=project_in)
    if not rowcount:  # 每次更新, 当前数据的更新时间会变, 只要id存在, 就会一直返回1
        raise IdNotExist(f"系统中不存在 id 为 {id} 的院系.")
    return resp_200(msg=f"更新了 id 为 {id} 的接口用例信息.")


@router.delete('/delete_project/{id}', response_model=Result, summary='通过 id 删除接口用例信息')
async def delete_project(id: int, db: AsyncSession = Depends(get_db)):
    rowcount = await project.remove(db, id)
    if not rowcount:
        raise IdNotExist(err_desc=f"系统中不存在 id 为 {id} 的接口用例.")
    return resp_200(msg=f'成功删除 id 为 {id} 的接口用例信息.')


@router.put('/updateStatus/{id}', response_model=Result, summary='通过id更新项目状态')
async def updateStatus(id: int, db: AsyncSession = Depends(get_db)):
    # 从数据库中获取项目记录
    project = await db.get(ProjectModel, id)
    if not project:
        raise IdNotExist(status_code=404, detail="项目不存在")
    # 取反状态字段
    project.status = not project.status
    # 提交更改到数据库
    await db.commit()
    return resp_200(msg="项目状态更新成功")

@router.get('/getProjectById', summary='通过id查询项目')
async def getProjectById(id: int, db: AsyncSession = Depends(get_db)):
    project_sql = await db.execute(select(ProjectModel).where(ProjectModel.id == id))
    project = project_sql.scalars().first()
    print(project)
    if not project:
        raise IdNotExist(status_code=404, detail="项目不存在")
    return {"code":200,"data":project,"msg":"查询成功"}
